package controller

import (
	"strconv"
	"time"

	"douyin/models"
	"douyin/repository/mysql"
	"douyin/service"
	"douyin/utils/pkg/jwt"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// Feed 视频流
func Feed(c *gin.Context) {
	//1.获取参数：时间戳，精确到秒
	qTime := c.Query("latest_time")
	token := c.Query("token") //从url获取，可能为空
	var userId int64          //默认0值
	if token != "" {          //如果token不为空，就能拿到userID
		MyClaims, _ := jwt.ParseToken(token)
		userId = MyClaims.UserID
	}
	latestTime, _ := strconv.ParseInt(qTime, 10, 64)
	if latestTime == 0 {
		//时间戳，如果为空，表示当前时间
		latestTime = time.Now().Unix()
	}
	//2. 业务处理
	videoList, nextTime, err := service.Feed(latestTime, userId)
	//查询空处理
	if err == mysql.ErrorQueryZeroRecord {
		zap.L().Error("service.Feed ErrorQueryZeroRecord!! ", zap.Error(err))
		models.ResponseFeedSuccess(c, nil, 0)
		return
	}
	//其他异常
	if err != nil {
		zap.L().Error("service.Feed failed", zap.Error(err))
		models.ResponseFeedError(c, models.CodeGetVideoFeedError)
		return
	}
	//3.返回响应
	//log.Println(nextTime, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
	models.ResponseFeedSuccess(c, videoList, nextTime)
}
